import os

from flask import Response
import mimetypes
from controllers.base_controllers import BaseController


def is_video(filename):
    video_extensions = ['.mp4', '.avi', '.mov', '.wmv', '.mkv', '.mp3']  # 支持的视频文件扩展名列表
    _, ext = os.path.splitext(filename)
    return ext.lower() in video_extensions


class FileController(BaseController):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get(self, file_name):
        mime_type, _ = mimetypes.guess_type(file_name)

        if is_video(file_name):
            def generate():
                video_path = './resumes/{}'.format(file_name)
                with open(video_path, 'rb') as video_file:
                    while True:
                        data = video_file.read(4096)  # 每次读取4KB
                        if not data:
                            break
                        yield data
            response = Response(generate(), mimetype=mime_type)
            response.headers['Content-Type'] = mime_type
            response.headers['Accept-Ranges'] = 'bytes'
            return response
        else:
            with open(r'./resumes/{}'.format(file_name), 'rb') as f:
                f = f.read()
                return Response(f, mimetype=mime_type)